package com.joysuch.wwyt.datadump.biz.processor;

import cn.hutool.core.collection.CollectionUtil;
import cn.zlg.common.datadump.annotation.DataDumpEntity;
import cn.zlg.common.datadump.processor.BaseExportEntityProcessor;
import cn.zlg.common.datadump.processor.BaseImportEntityProcessor;
import com.joysuch.wwyt.datadump.biz.model.EduQuestionDumpBean;
import com.joysuch.wwyt.edu.entity.EduQuestion;
import com.joysuch.wwyt.edu.entity.EduQuestionItem;
import com.joysuch.wwyt.edu.entity.dsl.QEduQuestion;
import com.joysuch.wwyt.edu.enums.QuestionTypes;
import com.joysuch.wwyt.edu.repository.EduQuestionItemDao;
import com.querydsl.core.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;

@Component
public class EduQuestionExportProcessor extends BaseExportEntityProcessor<EduQuestionDumpBean> {

    private static final Logger logger = LoggerFactory.getLogger(EduQuestionExportProcessor.class);

    @Autowired
    private EduQuestionItemDao questionItemDao;

    @Override
    public EduQuestionDumpBean processAfterTransformed(Tuple origin, EduQuestionDumpBean entity, DataDumpEntity annotation) {
        Long id = origin.get(QEduQuestion.eduQuestion.id);
        List<EduQuestionItem> items = questionItemDao.findByQuestionIdOrderByIndexNoAsc(id);
        if (CollectionUtil.isNotEmpty(items)) {
            for(int i=0; i < items.size() && i< 26; i++) {
                // 最多26个字母选项
                String content = items.get(i).getContent();
                setFieldValue("choice" + ((char)(i+'A')), entity, content);
            }
        }
        return entity;
    }

    private void setFieldValue(String s, EduQuestionDumpBean origin, String value) {
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(EduQuestionDumpBean.class, s);
        if(pd != null && pd.getReadMethod() != null ) {
            try {
               pd.getWriteMethod().invoke(origin, value);
            } catch (Exception e) {
                logger.error("写入选项{}错误", s);
            }
        }
    }

}
